<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <title>批量上传配置文件 v5</title>
    <style>
        body {
            font-family: "Segoe UI", sans-serif;
            background: #f4f6f8;
            padding: 30px;
            color: #333;
        }

        .container {
            max-width: 960px;
            background: #fff;
            padding: 25px 30px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            margin: auto;
        }

        h2 {
            text-align: center;
            margin-bottom: 20px;
            color: #2c3e50;
        }

        label {
            margin-top: 10px;
            display: block;
            font-weight: bold;
            color: #34495e;
        }

        input[type="text"], input[type="file"] {
            width: 100%;
            padding: 10px;
            margin-top: 5px;
            border: 1px solid #ccc;
            border-radius: 6px;
            font-size: 14px;
        }

        .button-group {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }

        button {
            background-color: #3498db;
            color: white;
            padding: 10px 16px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
        }

        button:hover {
            background-color: #2980b9;
        }

        #dropZone {
            margin-top: 25px;
            margin-bottom: 15px;
            border: 2px dashed #bbb;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            color: #888;
            transition: all 0.2s ease-in-out;
        }

        #dropZone.dragover {
            background-color: #e6f7ff;
            border-color: #3498db;
            color: #3498db;
        }

        progress {
            width: 100%;
            height: 20px;
            margin-top: 10px;
        }

        #progressText {
            display: block;
            text-align: right;
            margin-top: 5px;
            font-size: 14px;
            color: #666;
        }

        table {
            margin-top: 25px;
            width: 100%;
            border-collapse: collapse;
            background: #fafafa;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
        }

        th {
            background-color: #f0f0f0;
            color: #333;
        }

        td {
            font-size: 14px;
        }

        .success {
            color: green;
        }

        .fail {
            color: red;
        }

        .remove-btn {
            color: #e74c3c;
            cursor: pointer;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>批量上传配置文件 v5</h2>

    <label for="host">请求地址 (Host):</label>
    <input type="text" id="host" value="http://127.0.0.1:8081"/>

    <label for="accessToken">Access-Token:</label>
    <input type="text" id="accessToken" value="tuling"/>

    <label for="secret">Secret:</label>
    <input type="text" id="secret" value="$6UcJjE$T7iOP&o8"/>

    <label for="uid">UID:</label>
    <input type="text" id="uid" value="1001"/>

    <label for="platformCode">Platform Code:</label>
    <input type="text" id="platformCode" value="Inke"/>

    <div class="button-group">
        <label>
            📁 文件夹上传
            <input type="file" id="folderInput" webkitdirectory directory multiple style="display:none;"/>
        </label>
        <button onclick="document.getElementById('folderInput').click()">选择文件夹</button>

        <label>
            📄 多文件上传
            <input type="file" id="fileInput" multiple style="display:none;"/>
        </label>
        <button onclick="document.getElementById('fileInput').click()">选择多个文件</button>
    </div>

    <div id="dropZone">📂 拖拽多个 Excel 文件到这里添加到上传队列</div>

    <button style="margin-top: 10px;" onclick="uploadAllFiles()">上传所有文件</button>

    <progress id="progressBar" value="0" max="100"></progress>
    <span id="progressText">0%</span>

    <table id="uploadTable">
        <thead>
        <tr>
            <th>文件名</th>
            <th>状态</th>
            <th>版本号</th>
            <th>上传时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<script>
    const tableBody = document.querySelector('#uploadTable tbody');
    const fileMap = new Map(); // filename -> File

    // 读取本地参数
    window.onload = () => {
        ['host', 'accessToken', 'secret', 'uid', 'platformCode'].forEach(id => {
            const val = localStorage.getItem(id);
            if (val) document.getElementById(id).value = val;
        });
    };

    // 选择文件监听
    document.getElementById('folderInput').addEventListener('change', e => handleNewFiles(e.target.files));
    document.getElementById('fileInput').addEventListener('change', e => handleNewFiles(e.target.files));

    // 拖拽监听
    const dropZone = document.getElementById('dropZone');
    dropZone.addEventListener('dragover', e => {
        e.preventDefault();
        dropZone.classList.add('dragover');
    });
    dropZone.addEventListener('dragleave', () => {
        dropZone.classList.remove('dragover');
    });
    dropZone.addEventListener('drop', e => {
        e.preventDefault();
        dropZone.classList.remove('dragover');
        handleNewFiles(e.dataTransfer.files);
    });

    // 添加文件到队列
    function handleNewFiles(fileList) {
        const files = Array.from(fileList).filter(file => file.name.endsWith('.xls') || file.name.endsWith('.xlsx'));
        for (const file of files) {
            if (fileMap.has(file.name)) continue;
            fileMap.set(file.name, file);

            const row = document.createElement('tr');
            row.setAttribute('data-name', file.name);
            row.innerHTML = `
        <td>${file.name}</td>
        <td class="status">等待上传</td>
        <td class="version">-</td>
        <td class="time">-</td>
        <td><span class="remove-btn" onclick="removeFile('${file.name}')">❌</span></td>
      `;
            tableBody.appendChild(row);
        }
    }

    // 移除文件
    function removeFile(fileName) {
        fileMap.delete(fileName);
        const row = document.querySelector(`tr[data-name="${fileName}"]`);
        if (row) row.remove();
    }

    // 上传所有文件
    async function uploadAllFiles() {
        const host = document.getElementById('host').value.trim();
        const accessToken = document.getElementById('accessToken').value.trim();
        const secret = document.getElementById('secret').value.trim();
        const uid = document.getElementById('uid').value.trim();
        const platformCode = document.getElementById('platformCode').value.trim();
        const progressBar = document.getElementById('progressBar');
        const progressText = document.getElementById('progressText');

        // 保存参数
        ['host', 'accessToken', 'secret', 'uid', 'platformCode'].forEach(id => {
            localStorage.setItem(id, document.getElementById(id).value.trim());
        });

        if (!host || !accessToken || !secret || !uid || !platformCode) {
            alert('请填写所有必要信息');
            return;
        }

        const files = Array.from(fileMap.values());
        if (files.length === 0) {
            alert('上传队列为空');
            return;
        }

        let uploaded = 0;
        progressBar.value = 0;
        progressText.innerText = '0%';

        for (const file of files) {
            const row = document.querySelector(`tr[data-name="${file.name}"]`);
            const statusTd = row.querySelector('.status');
            const versionTd = row.querySelector('.version');
            const timeTd = row.querySelector('.time');

            statusTd.innerText = '上传中...';

            const formData = new FormData();
            formData.append('file', file, file.name);
            formData.append('platform_code', platformCode);

            try {
                const response = await fetch(`${host}/api/v0/configs/upload`, {
                    method: 'POST',
                    headers: {
                        'access-token': accessToken,
                        'secret': secret,
                        'uid': uid
                    },
                    body: formData
                });

                const res = await response.json();
                versionTd.innerText = res?.data || '失败';
                statusTd.innerText = res?.data ? '✅ 成功' : '❌ 失败';
                statusTd.className = res?.data ? 'status success' : 'status fail';
                timeTd.innerText = new Date().toLocaleString();
            } catch (err) {
                versionTd.innerText = '失败';
                statusTd.innerText = '❌ 上传失败';
                statusTd.className = 'status fail';
                timeTd.innerText = new Date().toLocaleString();
            }

            uploaded++;
            const percent = Math.round((uploaded / files.length) * 100);
            progressBar.value = percent;
            progressText.innerText = percent + '%';
        }
    }
</script>
</body>
</html>
